package com.tongtech.proxy.core.crypto;

import javax.net.ssl.*;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.SecureRandom;

public class SSLHandler {

    private static final String KEYSTORE_PATH = "path/to/keystore.jks";
    private static final String KEYSTORE_PASSWORD = "keystore_password";
    private static final String TRUSTSTORE_PATH = "path/to/truststore.jks";
    private static final String TRUSTSTORE_PASSWORD = "truststore_password";

    public static SSLContext createSSLContext() throws Exception {
        // Load keystore
        KeyStore keyStore = KeyStore.getInstance("JKS");
        try (InputStream keyStoreInput = new FileInputStream(KEYSTORE_PATH)) {
            keyStore.load(keyStoreInput, KEYSTORE_PASSWORD.toCharArray());
        }

        // Initialize KeyManagerFactory
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, KEYSTORE_PASSWORD.toCharArray());

        // Load truststore
        KeyStore trustStore = KeyStore.getInstance("JKS");
        try (InputStream trustStoreInput = new FileInputStream(TRUSTSTORE_PATH)) {
            trustStore.load(trustStoreInput, TRUSTSTORE_PASSWORD.toCharArray());
        }

        // Initialize TrustManagerFactory
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);

        // Initialize SSLContext
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());

        return sslContext;
    }

    public static SSLSocketFactory createSSLSocketFactory() throws Exception {
        SSLContext sslContext = createSSLContext();
        return sslContext.getSocketFactory();
    }

    public static HttpsURLConnection configureHttpsURLConnection(HttpsURLConnection connection) throws Exception {
        connection.setSSLSocketFactory(createSSLSocketFactory());
        connection.setHostnameVerifier((hostname, session) -> true); // Disable hostname verification
        return connection;
    }

    public static void getConnection() {
        try {
            SSLContext sslContext = SSLHandler.createSSLContext();
        } catch (Exception e) {

        }
    }
}

